package com.dingreading.cloud.web.controller;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.IpUtil;
import com.dingreading.cloud.common.util.aliyun.CdnUtil;
import com.dingreading.cloud.web.service.StudyVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/front/studyVideo")
@Api(tags = "习作视频管理")
public class StudyVideoController {

    @Resource
    private StudyVideoService studyVideoService;


    @ApiOperation(value = "获取cdn访问链接")
    @PostMapping(value = "/getCdnUrl")
    public R<Object> getCdnUrl(
            HttpServletRequest request,
            @ApiParam(value = "习作视频过期uid") @RequestParam(value = "uid") String uid
    ) throws Exception {
//        System.out.println("获取cdn访问链接");
        if (StringUtils.isBlank(uid)) {
            return R.fail("未传递视频标识");
        }
        String referer = request.getHeader("referer");
        if (StringUtils.isBlank(referer)) {
            return R.fail("未获取到访问来源");
        }
        if (!referer.contains(CdnUtil.PROD_REFERER) && !referer.contains(CdnUtil.TEST_REFERER)) {
            return R.fail("请求跨域了");
        }
        String ip = IpUtil.getIpAddr(request);
//        System.out.println("ip = " + ip);
//        String remoteAddr = request.getHeader("remote_addr");
//        System.out.println("remote_addr = " + remoteAddr);
//         remoteAddr = request.getParameter("remote_addr");
//        System.out.println("remote_addr = " + remoteAddr);
        if (StringUtils.isBlank(ip)) {
            return R.fail("未获取到客户端ip");
        }

        return studyVideoService.getCdnUrl(uid, ip);
    }


}